package BugzillaJsonRpc::User;
use 5.018;
use warnings;
use Config::Tiny;
use BugzillaJsonRpc::Client;

my $token_fpath = "$ENV{HOME}/.config/BugzillaJsonRpc.token";

use Data::Dumper;

sub login
{
	my ($params, $cb)= @_;
	BugzillaJsonRpc::Client::call("User.login", $params, sub {
		my ($ret) = @_;
		warn Dumper $ret;
		unless ( $ret->{error} )
		{
			my $token = $ret->{result}{token};
			warn 'login: get new access token';
			$ret->{result} = $token;
		}
		else
		{
			warn 'login: failed '. $ret->{error_message};
		}
		$cb->($ret);
	});
}

our $token;

sub autoLogin
{
	my $cfg = BugzillaJsonRpc::Config->new;
	my $cfg_sha1_hex = $cfg->getSha1Hex;

	if ( -f $token_fpath )
	{
		open TOKEN, '<', $token_fpath or die $!;
		chomp (my $cache_host = <TOKEN>);
		chomp (my $cache_sha1_hex = <TOKEN>);
		if ($cache_host eq $cfg->{host} && $cache_sha1_hex eq $cfg_sha1_hex)
		{
			$token = <TOKEN>;
			warn "autoLogin: any thing no change, get token from cache file";
		}
		else
		{
			warn "autoLogin: some things changed";
		}
		close TOKEN;
	}

	unless ($token)
	{
		Mojo::IOLoop->delay(
			sub {
				my ($delay) = @_;
				my $end = $delay->begin;

				login({ login => $cfg->{username}, password => $cfg->{password} },sub {
					my ($ret) = @_;
					$token = $ret->{result};
					$end->();
				});
			},
			sub {
				if ($token)
				{
					warn "autoLogin: write token to cache file";
					open TOKEN, '>', $token_fpath or die $!;
					say TOKEN $cfg->{host};
					say TOKEN $cfg_sha1_hex;
					print TOKEN $token;
					close TOKEN;
				}
				else
				{
					warn "autoLogin: login failed";
				}
			}
		)->wait;
	}

}


1;
